package managedbeans.administrator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import langresources.ResourcesController;
import managedbeans.GenericForumBean;
import utils.dataaccess.DBInterface;
import utils.dataaccess.IOUtil;


@ManagedBean(name="databaseSelectionBean")
@SessionScoped
public class DatabaseSelectionBean extends GenericForumBean implements Serializable{

    private HashMap<String,String> nameMapping = new HashMap<String, String>();
    
    private String hibernateConfigContent;

    public DatabaseSelectionBean() {
        nameMapping.put("Derby DB Datasource", "HibernateUtil");
        nameMapping.put("MySQL Datasource", "HibernateUtil");
        nameMapping.put("MongoBD Datasource", "NoSQLUtil");
    }
    
    public void selectDatasource(String datasourceName){
        DBInterface.setDatasourceClassName(nameMapping.get(datasourceName));
        showMessage(ResourcesController.extractResource("MESSAGE.INFO"), ResourcesController.extractResource("DATASOURCE_CHANGED_TO")+" "+datasourceName);
    }

    public ArrayList<String> getAvailableDatabases() {
        return new ArrayList(nameMapping.keySet());
    }

    public String getHibernateConfigContent() {
        File hibernateConfig = new File(IOUtil.getProjectRoot()+"WEB-INF/classes/hibernate.cfg.xml");
        return IOUtil.read(hibernateConfig); 
    }
    
    public void saveHibernateConfig(){
        File hibernateConfig = new File(IOUtil.getProjectRoot()+"WEB-INF/classes/hibernate.cfg.xml");
        IOUtil.write(hibernateConfig, this.hibernateConfigContent);
        showMessage(ResourcesController.extractResource("MESSAGE.INFO"), ResourcesController.extractResource("HIBERNATECONFIG_SAVED"));
    }

    public void setHibernateConfigContent(String hibernateConfigContent) {
        this.hibernateConfigContent = hibernateConfigContent;
        saveHibernateConfig();
    }
    
    

}
